package com.provider.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.domain.Pagination;
import com.domain.Provider;
import com.provider.dao.FindProviderDao;
import com.util.JdbcUtil;

public class FindProviderDaoImpl implements FindProviderDao {

	@Override
	public int findCount() {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		int count = 0;
		try {
			conn = JdbcUtil.getConnection();
			String sql = "select count(*) from providers";
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			rs.next();
			count = rs.getInt(1);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JdbcUtil.close(ps, rs);
		}
		return count;
	}

	@Override
	public List<Provider> findList(Pagination<Provider> pagination) {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		List<Provider> list = new ArrayList<>();
		try {
			conn = JdbcUtil.getConnection();
			String sql = "select * from (select p.*,rownum rn "
					+ "from (select * from providers order "
					+ "by provider_id) p) where rn "
					+ "between (?-1)*?+1 and ?*?";
			ps = conn.prepareStatement(sql);
			ps.setInt(1, pagination.getPage());
			ps.setInt(2, pagination.getLimit());
			ps.setInt(3, pagination.getPage());
			ps.setInt(4, pagination.getLimit());
			rs = ps.executeQuery();
			while(rs.next()){
				Provider p = new Provider();
				p.setId(rs.getInt(1));
				p.setName(rs.getString(2));
				p.setPhone(rs.getString(3));
				p.setAddress(rs.getString(4));
				p.setContent(rs.getString(5));
				list.add(p);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JdbcUtil.close(ps, rs);
		}
		return list;
	}

}
